package controller.cartp;

import com.zuche.framework.remote.RemoteClient;
import com.zuche.framework.remote.RemoteClientFactory;
import com.zuche.framework.remote.RemoteType;
import com.zuche.framework.tradingPlatform.GroupType;
import com.zuche.framework.tradingPlatform.ReplyRequestParams;
import com.zuche.framework.tradingPlatform.RequestParams;
import com.zuche.framework.tradingPlatform.TradingServiceExecutor;
import com.zuche.framework.utils.PropertiesReader;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by PCG on 2016/4/12.
 */
@Controller
public class kuaiqianController {

    private String projectAddress;

    public kuaiqianController() {
        this.projectAddress = PropertiesReader.getAppointPropertiesAttribute(
                "setting", "projectAddress", String.class);
    }

    /**
     * 信用卡发短信
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/kqcreateNoSms.do_")
    public void createNoSms(HttpServletRequest request,
                            HttpServletResponse response) throws IOException {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, "http://127.0.0.1:9080/cartptest/test/testRpcModeReturn.do_");

        paramMap.put(RequestParams.GROUP_TYPE, GroupType.CREATE_NO_SMS);
        paramMap.put(RequestParams.BUSINESS_MONEY,request.getParameter("money"));

        paramMap.put(RequestParams.CARD_TYPE, request.getParameter("cardType"));
        paramMap.put(RequestParams.CARD_NO, request.getParameter("cardNo"));
        paramMap.put(RequestParams.CREDITCARD_EXPIREMONTH, request.getParameter("month"));
        paramMap.put(RequestParams.CREDITCARD_EXPIREYEAR, request.getParameter("year"));
        paramMap.put(RequestParams.CREDITCARD_CVV, request.getParameter("cvv"));
        paramMap.put(RequestParams.PAYER_TEL,request.getParameter("mobile"));
        paramMap.put(RequestParams.PAYER_NAME, request.getParameter("name"));
        paramMap.put(RequestParams.IDENTITY_ID, request.getParameter("sfz"));
        paramMap.put(RequestParams.SOURCE_ID, request.getParameter("sourceId"));


        paramMap.put(RequestParams.IDENTITY_TYPE,"0");
        paramMap.put(RequestParams.NATION_CODE, "");
        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));
        paramMap.put(RequestParams.DIRECT_CARD, "1");//信用卡直接交易
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//租车账户

        paramMap.put(RequestParams.IS_VALIDATE, "true");
        doRpc(request, response, paramMap);
    }


    /**
     * 信用卡首次快捷支付
     * @param request
     * @param response
     */
    @RequestMapping("/kqEposPaySms.do_")
    public void testEposPaySms(HttpServletRequest request,
                               HttpServletResponse response) {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                + "/rpcReturn.do_");
        paramMap.put(RequestParams.GROUP_TYPE, GroupType.EPOS_PAY_SMS);
        paramMap.put(RequestParams.VALID_CODE,  request.getParameter("validCode"));
        paramMap.put(RequestParams.TOKEN, request.getParameter("token"));
        paramMap.put(RequestParams.RECORD_ID, request.getParameter("recordId"));

        paramMap.put(RequestParams.IS_VALIDATE, request.getParameter("isValidate"));//是否需要绑卡。
        //专车区分是 1:首页绑卡,还是2:充值页面绑卡（租车不传）
        paramMap.put("tp_is_autopay",request.getParameter("autopay"));
        //如果是使用PCI方式，首次支付传0，再次支付传1
        paramMap.put("tp_is_PCI",request.getParameter("isPCI"));//增加了这个参数
        paramMap.put("tp_only_bind","true");//是否只做绑定（true:绑卡，false：绑卡加消费）

        paramMap.put(RequestParams.CARD_TYPE, request.getParameter("cardType"));
        paramMap.put(RequestParams.CARD_NO, request.getParameter("cardNo"));
//		paramMap.put(RequestParams.CARD_NO, "6258091642911270");
        paramMap.put(RequestParams.CREDITCARD_EXPIREMONTH, request.getParameter("month"));
        paramMap.put(RequestParams.CREDITCARD_EXPIREYEAR, request.getParameter("year"));
        paramMap.put(RequestParams.CREDITCARD_CVV, request.getParameter("cvv"));
        paramMap.put(RequestParams.PAYER_TEL,request.getParameter("mobile"));
        paramMap.put(RequestParams.PAYER_NAME, request.getParameter("name"));
        paramMap.put(RequestParams.IDENTITY_ID, request.getParameter("sfz"));
        paramMap.put(RequestParams.SOURCE_ID, request.getParameter("sourceId"));

        paramMap.put(RequestParams.NATION_CODE, "");
        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));
        paramMap.put(RequestParams.DIRECT_CARD, "1");
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//付款账户//0:租车,1:专车

        doRpc(request, response, paramMap);
    }

    /**
     * 二次快捷支付（储蓄卡，信用卡）
     * @param request
     * @param response
     */
    @RequestMapping("/kqEposPaySms2.do_")
    public void testEposPaySms2(HttpServletRequest request,
                                HttpServletResponse response) {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                + "/rpcReturn.do_");
        paramMap.put(RequestParams.GROUP_TYPE, GroupType.EPOS_PAY_SMS);

        //------begin------PCI方式需要的参数------begin------
        //如果是使用PCI方式，首次支付传0，再次支付传1
//        paramMap.put("tp_is_PCI","1");
//        paramMap.put(RequestParams.CARD_NO,"622575******7996");//短卡号，卡号中间的星号一起传递过来
//        paramMap.put(RequestParams.SOURCE_ID,"CMB");//银行简称
//        paramMap.put(RequestParams.PAYER_ID, "5125392");//交易人ID
        //-------end-------PCI方式需要的参数-------end-------

        //------begin------专车cartp存放绑卡信息情况下需要的参数-------------
        paramMap.put(RequestParams.BIND_ID, "33727");//33634,33633
        //-------end-------专车cartp存放绑卡信息情况下需要的参数---------

        paramMap.put(RequestParams.BUSINESS_MONEY, "1");
        paramMap.put(RequestParams.BUSINESS_ID, ""+System.currentTimeMillis());
        paramMap.put(RequestParams.BUSINESS_NAME, "ucarcdms");
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//0:租车,1:专车
        paramMap.put(RequestParams.IS_TEST, "TRUE");
        doRpc(request, response, paramMap);
    }


    /**
     * 储蓄卡发短信
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/kqcreateNoSms2.do_")
    public void createNoSms2(HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.GROUP_TYPE, GroupType.CREATE_NO_SMS);

        paramMap.put(RequestParams.CARD_NO, request.getParameter("cardNo"));//6226632100897524,6228270021221208879
        paramMap.put(RequestParams.CARD_TYPE, request.getParameter("cardType"));//必填，cartp默认为信用卡
        paramMap.put(RequestParams.PAYER_TEL, request.getParameter("mobile"));
        paramMap.put(RequestParams.IDENTITY_ID, request.getParameter("sfz"));
        paramMap.put(RequestParams.PAYER_NAME, request.getParameter("name"));
        paramMap.put(RequestParams.SOURCE_ID, request.getParameter("sourceId"));
        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));

        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));
        doRpc(request, response, paramMap);
    }

    /**
     * 储蓄卡快捷支付
     * @param request
     * @param response
     */
    @RequestMapping("/kqEposPaySms3.do_")//
    public void testEposPaySms3(HttpServletRequest request,
                                HttpServletResponse response) {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                + "/rpcReturn.do_");
        paramMap.put(RequestParams.GROUP_TYPE, GroupType.EPOS_PAY_SMS);
        paramMap.put(RequestParams.VALID_CODE,  request.getParameter("validCode"));
        paramMap.put(RequestParams.TOKEN, request.getParameter("token"));
        paramMap.put(RequestParams.RECORD_ID, request.getParameter("recordId"));

        //专车区分是 1:首页绑卡,还是2:充值页面绑卡（租车不传）
        paramMap.put("tp_is_autopay",request.getParameter("autopay"));
        paramMap.put(RequestParams.IS_VALIDATE, request.getParameter("isValidate"));//是否需要绑卡

        paramMap.put(RequestParams.CARD_TYPE, request.getParameter("cardType"));
        paramMap.put(RequestParams.CARD_NO, request.getParameter("cardNo"));
        paramMap.put(RequestParams.PAYER_TEL,request.getParameter("mobile"));
        paramMap.put(RequestParams.PAYER_NAME, request.getParameter("name"));
        paramMap.put(RequestParams.IDENTITY_ID, request.getParameter("sfz"));
        paramMap.put(RequestParams.SOURCE_ID, request.getParameter("sourceId"));

        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//付款账户//0:租车,1:专车

        doRpc(request, response, paramMap);
    }


    //快捷再次支付短信
    @RequestMapping("/kqQuickPaySms2.do_")
    public void testQuickPaySms2(HttpServletRequest request,
                                 HttpServletResponse response) {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                + "/rpcReturn.do_");
        paramMap.put(RequestParams.GROUP_TYPE, "eposQuickPaySms");
//        paramMap.put(RequestParams.PAYER_ID, "105125100");//
//        paramMap.put(RequestParams.BIND_ID, "33633");//33634,33633
        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));//
        paramMap.put(RequestParams.BIND_ID, "33772");//33634,33633
        paramMap.put(RequestParams.BUSINESS_MONEY, "1");
//        paramMap.put(RequestParams.BUSINESS_ID, "10141272511504");
        paramMap.put(RequestParams.BUSINESS_ID, ""+System.currentTimeMillis());
        paramMap.put(RequestParams.BUSINESS_NAME, "ucarcdms");
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));//支付账户
        paramMap.put(RequestParams.IS_TEST, "TRUE");
        doRpc(request, response, paramMap);
    }

    //快捷在次支付
    @RequestMapping("/kqEposSecQuickPay.do_")
    public void testEposSecQuickPay(HttpServletRequest request,
                                    HttpServletResponse response) {
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                + "/rpcReturn.do_");
        paramMap.put(RequestParams.GROUP_TYPE, "eposReQuickPay");
        paramMap.put(RequestParams.PAYER_ID, request.getParameter("payerId"));//
        paramMap.put(RequestParams.BIND_ID, "33772");//33634,33633
        paramMap.put(RequestParams.BUSINESS_MONEY, "1");
        paramMap.put(RequestParams.BUSINESS_ID, ""+System.currentTimeMillis());
        paramMap.put(RequestParams.BUSINESS_NAME, "ucarcdms");
        paramMap.put(RequestParams.SYS_GROUP, request.getParameter("sysGroup"));

        paramMap.put(RequestParams.VALID_CODE,  request.getParameter("validCode"));
        paramMap.put(RequestParams.TOKEN, request.getParameter("token"));
        paramMap.put(RequestParams.RECORD_ID, request.getParameter("recordId"));
        doRpc(request, response, paramMap);
    }


    /**
     * 查询绑卡信息
     */
    @RequestMapping("/kqQueryBind.do_")
    @ResponseBody
    public Object testQueryBind(HttpServletRequest request){
        Boolean isDriver =false;
        String payerId ="5133132";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("payerId", payerId);
        map.put("cardType","0");
        map.put("isDriver", isDriver);
        map.put("tp_is_autopay",false);
        final String  url = "http://paytest03.10101111.com:9080/cartp";
        final RemoteClient client = RemoteClientFactory.getInstance(url, RemoteType.HESSIAN);
        Object obj;
        if(isDriver){
            obj = client.executeToObject("cartp.creditcardbind.query", map);//查询司机绑卡信息，需要 isDriver参数
        }else{
            obj = client.executeToObject("cartp.creditcardbind.queryId", payerId);//只对专车起作用
        }
        return obj;
    }

    /**
     * 快钱支持银行
     * @return
     */
    @RequestMapping("/kqQuerySupport.do_")
    @ResponseBody
    public Object testQuerySupport(){
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(RequestParams.SYS_GROUP, "1");
//        paramMap.put(RequestParams.CARD_TYPE,"2");//1,一键支付2,网银
        paramMap.put(RequestParams.GROUP_TYPE,GroupType.QUERY_SUPPORT);
        paramMap.put(RequestParams.TARGET_GROUP,GroupType.DRAWING);
//        paramMap.put(RequestParams.TARGET_GROUP,"easyLinkWebPay");
        Map<String,String> result = TradingServiceExecutor.doRpc(paramMap, true);
        return result;
    }


    /**
     * 快钱退款
     * @param request
     * @param response
     */
    @RequestMapping("/kqRefundRpcMode.do_")
    @ResponseBody
    public void testRpcMode(HttpServletRequest request,HttpServletResponse response){
        Map<String,String> paramMap = new HashMap<String,String>();
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter out = null;
        try {
            out=response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filePath = "E:\\文档\\交易接口文档\\A.退款相关\\20160923\\20160923pre.txt";
        //结合上面退款生成paramMap,从文件读入多条记录退款
        Map<String, String> map = new HashMap<String, String>();
        try {
            paramMap.put(RequestParams.GROUP_TYPE, GroupType.EPOS_PAY_REFUND);//先取消后退款GroupType.EPOS_PAY_CANCEL,EPOS_PAY_REFUND
            paramMap.put(RequestParams.ASYNC_REPLY_URL,"http://10.101.32.9:8083/cartptest/testCartp/testMvcModeReturn.do_");
            FileReader file = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(file);
            String input;
            int i =1;
            while((input=reader.readLine())!=null){
                String[] s = input.split("\t");
                paramMap.put(RequestParams.RECORD_ID, s[0]);
                paramMap.put(RequestParams.BUSINESS_MONEY,s[1]);
                paramMap.put(RequestParams.SYS_GROUP,s[2]);
                Map<String,String> result=TradingServiceExecutor.doRpc(paramMap,false);
                System.out.println("第i个的结果是i=："+  i++   +"&&&&&===="+result.get(ReplyRequestParams.STATUS));
                if (result.get(ReplyRequestParams.STATUS).equals("0")) {
                    map.put(s[0],s[1]);
                }
                out.println(JSONArray.fromObject(result));
            }
            System.out.println("xx:"+ JSONArray.fromObject(map));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 信用卡预授权撤单
     * @param request
     * @param response
     */
    @RequestMapping("/kqAuthCancel.do_")
    public void testAuthCancel(HttpServletRequest request,
                               HttpServletResponse response) {
        Map<String,String> paramMap = new HashMap<String,String>();
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter out = null;
        try {
            out=response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filePath = "E:\\文档\\交易接口文档\\A.退款相关\\2016-05-20 wangsong refund.txt";
        //结合上面退款生成paramMap,从文件读入多条记录退款
        Map<String, String> map = new HashMap<String, String>();
        try {
            paramMap.put(RequestParams.GROUP_TYPE, GroupType.EPOS_AUTH_CANCEL);
            paramMap.put(RequestParams.CUSTOMIZED_FLAG + "selfParam", "liqingyuan");
            paramMap.put(RequestParams.ASYNC_REPLY_URL, projectAddress
                    + "/rpcReturn.do_");
            paramMap.put(RequestParams.SYS_GROUP, "1");
            FileReader file = new FileReader(filePath);
            BufferedReader reader = new BufferedReader(file);
            String input;
            int i =1;
            while((input=reader.readLine())!=null) {
                String[] s = input.split("\t");
                paramMap.put(RequestParams.RECORD_ID, s[0]);
                Map<String, String> result = TradingServiceExecutor.doRpc(paramMap, false);
                System.out.println("第个的结果是" + i++ + "&&&&&====" + result.get(ReplyRequestParams.STATUS));
                if (result.get(ReplyRequestParams.STATUS).equals("0")) {
                    map.put(s[0], s[1]);
                }
                out.println(JSONArray.fromObject(result));
            }
            System.out.println("error:"+ JSONArray.fromObject(map));
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private void doRpc(HttpServletRequest request,
                       HttpServletResponse response, Map<String, String> paramMap) {
        Map<String, String> result = TradingServiceExecutor.doRpc(paramMap,
                true);
        try {
            response.setContentType("text/html;charset=UTF-8");
            StringBuilder sb = new StringBuilder("");
            for (Field f : ReplyRequestParams.class.getDeclaredFields()) {
                if (result.containsKey(f.get(null).toString())) {
                    sb.append(f.getName()).append(" = ")
                            .append(result.get(f.get(null).toString()))
                            .append("<br/>");
                }
            }
            for (String key : result.keySet()) {
                if (key.startsWith(RequestParams.CUSTOMIZED_FLAG)) {
                    sb.append(key).append(" = ").append(result.get(key));
                }
            }
            response.getWriter().write(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
